import React, {
  useEffect,
  useState,
  useRef,
  forwardRef,
  useImperativeHandle,
  useCallback,
  useMemo,
  useContext,
} from "react";
// import { DevPopup, LayoutB } from "~/public/cpas-ui";
// import { Button, TextBox } from "devextreme-react";
import "./index.less";

import {
  TreeList, Selection, Column
} from 'devextreme-react/tree-list';
import AntTabs, {
  HocVerticalLeftStyleTab,
} from "~/public/cpas-ui/components-ui/ant-components/AntTab";
import { useModel } from "umi";


import { getDataListEx, getSubjectType } from './service'
import AudDialog from "@/pages/components/Aud/AudDialog";
import { moneyFormat } from "@/utils";
import { SpecificPupopContext } from "./index";
import { Guid, guid } from "guid-factory/lib/Guid";
import notify from "devextreme/ui/notify";
import { LoadIndicator } from "devextreme-react";

export const BatchAddSubjectPopup = forwardRef((props: any, ref: any) => {
  // console.log("执行组件--------");

  const { whereFrom } = props;
  const { initialState } = useModel('@@initialState');
  const { entryParamData } = useContext<any>(SpecificPupopContext);
  const { curDataYearData_ID: AccountDataID, curDataBillID, adjustChanged } = entryParamData;

  const { dbname } = initialState?.curPart;
  const diaParams = useRef<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const [isShowGloablLoadBOX, setIsShowGlobalLoadBOX] = useState<boolean>(false);
  const [entryFilterTreeData, setEntryFilterTreeData] = useState<any[]>([]);// 树的过滤数据
  const [TbsStates, setTbsStates] = useState<any>("0");
  const TreeListRef = useRef<any>();
  const [entryTabsData, setEntryTabsData] = useState<any[]>([]);
  const entryTreeDataRef = useRef<any>();
  // const [startupSelectedKeys, setStartupSelectedKeys] = useState<any>([]);
  const [scrollTop, setScrollTop] = useState(0);
  // const [selectedKeys, setSelectedKeys] = useState<string[]>([]); // 存储选中项的 GUID
  // const [selectedKeys, setSelectedKeys] = useState(new Set()); // 存储选中项的 GUID
  // const [filteredData, setFilteredData] = useState([]);



  // const [selectedKeys, setSelectedKeys] = useState<any>(new Set()); // 全局选中项
  // const [currentSelectedKeys, setCurrentSelectedKeys] = useState<any[]>([]); // 当前过滤条件下的选中项

  const [selectedKeys, setSelectedKeys] = useState({}); // 存储所有条件下的选中项

  const tableScrollTo0 = () => {
    const leftTreeViewScrollView = TreeListRef?.current?.instance?.getScrollable();
    if (leftTreeViewScrollView) {
      // leftTreeViewScrollView.scrollTop();
      // setValue("");
      TreeListRef.current.instance.searchByText();
      TreeListRef?.current?.instance?.clearSelection();
      leftTreeViewScrollView.scrollTo({ left: 0, top: 0 });
      setIsShowGlobalLoadBOX(false);
    }
  };

  // 获取表格数据
  const getSubjectSDBDatas = async (DataId: any) => {
    entryTreeDataRef.current = [];
    // console.log(AccountDataID, curDataBillID, adjustChanged, '@@@');
    setIsShowGlobalLoadBOX(true);

    const res = await getDataListEx({
      dbname,
      Data_ID: DataId,
      isHasFZZ: true,
    });
    if (res.success) {
      entryTreeDataRef.current = res.data;
      setEntryFilterTreeData(res.data);
      setTbsStates('0');
      setIsShowGlobalLoadBOX(false);
    } else {
      setEntryFilterTreeData([]);
      setIsShowGlobalLoadBOX(false);
    }
    tableScrollTo0();
  };


  const getSubjectTypeData = async (DataId: any) => {
    const res = await getSubjectType({
      dbname,
      Data_ID: DataId,
    });
    if (res.success) {
      res.data.unshift({ code: "0", type: "全部" });
      setEntryTabsData(res.data);
      // console.log(res.data, '@@@');
      setTbsStates('0');
    }
  };

  // 自定义方法
  useImperativeHandle(ref, () => ({
    show: async (params: any) => {
      diaParams.current = params;
      setVisible(true);
      setSelectedKeys({});
      // setStartupSelectedKeys([]);
      getSubjectSDBDatas(params.args.Data_ID);
      getSubjectTypeData(params.args.Data_ID);
    },
  }));


  const closePopup = () => {
    // setValue("");
    setIsShowGlobalLoadBOX(false);
    setVisible(false);
    setTbsStates("0");
    if (TreeListRef.current) {
      TreeListRef.current.instance.searchByText();
      TreeListRef.current.instance.clearSelection();
    }
    diaParams.current.cancelCallback();

  };

  // 右侧 切换方法
  const getSubjectListData = useCallback((r: string) => {
    const resF = entryTabsData.filter((item: any) => r === item.code);
    const filStr = resF[0]?.type ?? '全部';
    setTbsStates(r);
    if (entryTreeDataRef.current?.length) {
      if (filStr === "全部") {
        setEntryFilterTreeData(entryTreeDataRef.current);
      } else {
        const KMLXData = entryTreeDataRef.current.filter((item: any) => {
          return item.KMLX && item.KMLX.includes(filStr)
        });
        setEntryFilterTreeData(KMLXData);
      }
    }
    return true;
  }, [entryTreeDataRef.current, entryTabsData]);



  // const isLeafNode = useCallback((nodeId: any) => {
  //   return !entryFilterTreeData.some(employee => employee.PID === nodeId);
  // }, [entryFilterTreeData]);
  // const customizeSelectionCell = useCallback((cellElement: any, cellInfo: any) => {
  //   console.log("cellInfo", cellElement, cellInfo);
  //   // const isLeaf = isLeafNode(cellInfo.key);
  //   // const checkbox = cellElement.querySelector('.dx-select-checkbox');
  //   // if (checkbox && !isLeaf) {
  //   //   checkbox.disabled = true;
  //   // }
  // }, [isLeafNode]);


  // const onSelectionChanged = useCallback((e) => {
  //   const newSelectedRowKeys = e.selectedRowKeys.filter(key => isLeafNode(key));
  //   setSelectedRowKeys(newSelectedRowKeys);
  // }, [isLeafNode]);



  const funEntryAddData = (cellClickData: any, arrIndex: number) => {
    /*
      调整分录批量选择科目“余额”的规则
        1、科目方向“借方” ，余额“正”数时，自动把余额带入调整分录“贷方金额”列；余额“负”数时，自动把余额带入调整分录“借方金额”列。
        2、科目方向“贷方” ，余额“正”数时，自动把余额带入调整分录“借方金额”列；余额“负”数时，自动把余额带入调整分录“贷方金额”列。
          赋值时，要将金额赋值成绝对值。
          期初的  --->QCSDS 
          期末的  --->SDS
    */

    // 获取调整分录金额的辅助函数
    const getAdjustedAmount = (amount: number, accountDirection: string) => {
      let debitJF: number | null = null; // 借方
      let creditDF: number | null = null; // 贷方
      if (accountDirection === "借") {
        if (amount > 0) {
          creditDF = amount;
        } else if (amount < 0) {
          debitJF = Math.abs(amount);
        }
      } else {
        if (amount > 0) {
          debitJF = amount;
        } else if (amount < 0) {
          creditDF = Math.abs(amount);
        }
      }
      return { creditDF, debitJF };
    };

    let tempDF: number | null = null;  // 贷方
    let tempJF: number | null = null; // 借方
    const amount = adjustChanged === '0' ? cellClickData.QCSDS : cellClickData.SDS;
    const { creditDF, debitJF } = getAdjustedAmount(amount, cellClickData.KMFX);
    tempDF = creditDF;
    tempJF = debitJF;

    const myId: guid = Guid.newGuid();
    let source8: any;
    let cellDbData: any;
    const source1 = cellClickData;
    const source2 = { XH: arrIndex }; //序号
    const source3 = { DF: tempDF }//贷方
    const source4 = { JF: tempJF }; //借方
    const source5 = { remark: '' }; //备注
    const source6 = { GUID: myId }; //GUID
    const source7 = { billID: curDataBillID }; //billID
    if (whereFrom === '账表调整') {
      source8 = { isHCFSE: 0 }; //红冲
      cellDbData = Object.assign(source1, source2, source3, source4, source5, source7, source6, source8);
    } else {
      cellDbData = Object.assign(source1, source2, source3, source4, source5, source7, source6);
    };
    return cellDbData;
  };

  const batchAdd_Fun = async (leavesOnlyData: any[]): Promise<void> => {
    let treeListData: any[] = [];
    const leavesOnlyFilter = leavesOnlyData.filter((item: any) => !item.itemNames3);
    const leavesOnly = leavesOnlyData.filter((item: any) => item.itemNames3);

    if (leavesOnlyFilter.length > 0) {
      notify("此科目未对应报表项目，请先对科目进行对应后，再进行调整", "error", 2000);
    }

    console.time();
    treeListData = leavesOnly.map((element, arrIndex) => {
      return funEntryAddData(element, arrIndex);
    });
    const batchRes = await diaParams.current?.okCallback(treeListData);
    // console.log('@@@', batchRes);
    setTimeout(() => {
      if (batchRes) {
        closePopup();
        console.timeEnd();
      }
    }, 1000);


  };


  const onSelectionChangeds = useCallback(async (e: any) => {
    // 保存当前滚动位置
    setScrollTop(TreeListRef.current.instance.getScrollable().scrollTop());
    setSelectedKeys((prevSelectedKeys) => {
      const newSelectedKeys = { ...prevSelectedKeys };
      if (TbsStates !== '0') {
        newSelectedKeys[TbsStates] = e.selectedRowKeys;
        let newSelectedKeysSet = new Set(newSelectedKeys['0']);
        e.selectedRowKeys.forEach((key: string) => newSelectedKeysSet.add(key));
        newSelectedKeys['0'] = Array.from(newSelectedKeysSet);
      } else {
        const foundItem = e.selectedRowsData.find((item: any) => item.ID === e.currentSelectedRowKeys[0]);
        if (foundItem?.ID) {
          const resF = entryTabsData.find((item: any) => foundItem?.KMLX && foundItem?.KMLX === item.type);
          const codeStr = resF?.code ?? '0';
          let newSelectedKeysSet = new Set(newSelectedKeys[codeStr]);
          e.selectedRowKeys.forEach((key: string) => newSelectedKeysSet.add(key));
          newSelectedKeys[codeStr] = Array.from(newSelectedKeysSet);
        }
        newSelectedKeys[TbsStates] = e.selectedRowKeys;
      }
      return newSelectedKeys;
    });

  }, [TbsStates, entryTabsData]);



  useEffect(() => {
    // 在选中行状态更新后恢复滚动位置
    if (TreeListRef.current) {
      const scrollable = TreeListRef.current?.instance.getScrollable();
      if (scrollable) {
        scrollable?.scrollTo({ top: scrollTop }) ?? console.log('@@@ 还没创建DevTable');;
      }
    }
  }, [selectedKeys, scrollTop]);

  return (
    <>
      <AudDialog
        visible={visible}
        title={diaParams.current?.args?.title}
        minWidth={1250}
        minHeight={730}
        height="70vh"
        width="60vw"
        showzuidahuaButton={false}
        showCancelButton={true}
        showOkButton={true}
        onHiding={() => {
          if (isShowGloablLoadBOX) return;
          closePopup();
        }}

        onOK={async () => {
          if (isShowGloablLoadBOX) return;
          if (diaParams.current?.okCallback) {
            setIsShowGlobalLoadBOX(true);
            const res = getSubjectListData("0");
            if (res) {
              await TreeListRef.current?.instance.selectRows(selectedKeys['0']);
              setTimeout(() => {
                const leavesOnlyData = TreeListRef.current?.instance.getSelectedRowsData("leavesOnly");
                if (leavesOnlyData.length === 0) {
                  closePopup();
                } else {
                  batchAdd_Fun(leavesOnlyData);
                }
                console.log(leavesOnlyData, '@@@');
                setIsShowGlobalLoadBOX(false);

              }, 1000);

            }
          }
        }}
        onCancel={() => {
          if (isShowGloablLoadBOX) return;
          closePopup();
        }}
      >
        {/* {layoutBContainer} */}

        <div style={{ position: "relative", width: '100%', height: '100%', padding: '1px', display: 'flex', justifyContent: 'center', alignItems: 'center' }}
          className="batchSubjectTreeBox">
          {

            useMemo(() => {
              console.log('@@@ useMemo', isShowGloablLoadBOX);

              if (isShowGloablLoadBOX) {
                return <div style={{
                  position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
                  opacity: 0.5, zIndex: "99999", background: "#ddd"
                }}>
                  <LoadIndicator id="medium-indicator" height={50} width={50} />
                </div>
              }
              return;
            }, [isShowGloablLoadBOX])
          }

          <TreeList
            className="PublicTreeList"
            ref={TreeListRef}
            dataSource={entryFilterTreeData}
            allowColumnResizing={true}
            showBorders={true}
            showRowLines={true}
            columnResizingMode="widget"
            columnMinWidth={100}
            parentIdExpr="PID"
            keyExpr="ID"
            height="100%"
            rootValue='0'
            width='calc(100% - 45px)'
            // onCellClick={onCellClick}
            // onContentReady={contentReady}
            // onCellDblClick={onCellDblClick}
            // onSelectionChanged={(e) => {
            //   const { currentSelectedRowKeys } = e;
            //   // const newSelectedRowKeys = e.selectedRowKeys.filter(key => isLeafNode(key));
            //   console.log("触发----------", e, currentSelectedRowKeys);
            //   // setSelectState(false);
            // }}
            // 显示斑马线
            rowAlternationEnabled={true}
            // onContextMenuPreparing={relationMenuItems}
            // selectedRowKeys={startupSelectedKeys}
            // onSelectionChanged={onSelectionChangeds}
            loadPanel={{
              enabled: true,
              text: 'Loading...',
            }}
            selectedRowKeys={selectedKeys[TbsStates]}
            onSelectionChanged={onSelectionChangeds}
            searchPanel={{
              visible: true,
              width: 180,
              placeholder: '',
            }}
            // onFocusedCellChanging={(data: any) => {

            //   const res = TreeListRef.current?.instance.getKeyByRowIndex(data.newRowIndex)
            //   const res1 = TreeListRef.current?.instance.getRowIndexByKey(res);
            //   console.log(res, res1, data, '@@@');
            // }}
            toolbar={{
              items: [
                {
                  cssClass: 'searchPanel_Style',
                  location: 'after',
                  name: 'searchPanel',
                },
                {
                  location: 'after',
                  widget: 'dxButton',
                  cssClass: 'refreshButton_Style',
                  options: {
                    icon: "iconfont icon-refresh",
                    onClick: () => {
                      getSubjectSDBDatas(AccountDataID);
                    },
                  },
                },
              ],
            }}
          >
            <Selection recursive={true} mode="multiple" allowSelectAll={false} />
            {/* <Column
              dataField="KMBH"
              caption="科目编号"
              width={130}
              alignment="left"
            /> */}
            <Column
              dataField="displayName"
              caption="科目名称"
              alignment="left"
            />
            <Column
              dataField="itemNames3"
              caption="对应报表项目"
              width={200}
              alignment="left"
            />

            <Column
              dataField="KMFX"
              caption="科目方向"
              width={80}
              alignment="center"
            />
            <Column
              dataField="QCSDS"
              caption="期初余额"
              width={120}
              alignment="right"
              dataType="number"
              // dataTypeCustom="dataTypeCustom"
              // editorOptions={{
              //   format: { type: 'decimal', currency: 'CNY', precision: 2 },
              // }}
              cellRender={(cell: any) => {
                return cell.data.QCSDS ? moneyFormat(cell.data.QCSDS) : "";
              }}
            />
            <Column
              dataField="SDS"
              caption="期末余额"
              width={120}
              alignment="right"
              dataType="number"
              cellRender={(cell: any) => {
                return cell.data.SDS ? moneyFormat(cell.data.SDS) : "";
              }}
            // dataTypeCustom="dataTypeCustom"
            // editorOptions={{
            //   format: { type: 'decimal', currency: 'CNY', precision: 2 },
            // }}
            />

          </TreeList>

          <HocVerticalLeftStyleTab
            activeKey={TbsStates}
            className='AccountSubjectsTabs'
            tabPosition='right'
            tabBarStyle={{ background: '#FFF' }}
            onChange={getSubjectListData}
          >
            {Array.isArray(entryTabsData) ?
              entryTabsData.map((item: any) => {
                return <AntTabs.Panel
                  tab={item.type}
                  key={item.code}
                  style={{ marginTop: "5px" }}
                />
              })
              : <></>
            }
          </HocVerticalLeftStyleTab >
        </div>
      </AudDialog >
    </>
  );
});

export default BatchAddSubjectPopup;
